package com.farmer.common.utils;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import static com.farmer.common.constants.Common.*;


/**
 * 七牛云
 * 上传单张图片工具类
 */
public class UploadPicUtils {

    /**
     * 上传图片
     * @param file
     * @return
     */
    public static String uploadPicture(MultipartFile file) {
        try {
            Configuration config = new Configuration(Zone.zone0());
            UploadManager manager = new UploadManager(config);
            Auth auth = Auth.create(AK, SK);
            String token = auth.uploadToken(BK);
            Response response = manager.put(file.getInputStream(), file.getOriginalFilename(), token, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            //根据文件名获取七牛云存储链接
            return getFilePath(putRet.key);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取图片链接
     * @param fileName
     * @return
     */
    public static String getFilePath(String fileName) {
        String publicUrl = DN + fileName;
        /**
         * 空间为私有访问，需要验证 token
         Auth auth = Auth.create(AK, SK);
         long expireInSeconds = 3600; //1小时，可以自定义链接过期时间
         String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
         */
        return publicUrl;
    }
}
